package com.xjrsoft.module.visual.service.impl;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xjrsoft.common.core.SplicingConnectionString;
import com.xjrsoft.common.helper.DbHelper;
import com.xjrsoft.common.helper.DbHelperFactory;
import com.xjrsoft.module.visual.dto.DynamicQueryDto;
import com.xjrsoft.module.visual.dto.SaveVisualDbVo;
import com.xjrsoft.module.visual.dto.TestDbDto;
import com.xjrsoft.module.visual.entity.XjrVisualConfig;
import com.xjrsoft.module.visual.entity.XjrVisualDb;
import com.xjrsoft.module.visual.mapper.XjrVisualDbMapper;
import com.xjrsoft.module.visual.service.IXjrVisualDbService;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

@Service
public class XjrVisualDbService extends ServiceImpl<XjrVisualDbMapper, XjrVisualDb> implements IXjrVisualDbService {
    @Override
    public Boolean testConnectionDb(TestDbDto dto) throws SQLException, ClassNotFoundException {
        DbType dbType = DbType.MYSQL;
        if(dto.getDriverClass().contains("mysql")){
            dbType = DbType.MYSQL;
        }
        if(dto.getDriverClass().contains("sqlserver")){
            dbType = DbType.SQL_SERVER;
        }  if(dto.getDriverClass().contains("postgresql")){
            dbType = DbType.POSTGRE_SQL;
        }  if(dto.getDriverClass().contains("oracle")){
            dbType = DbType.ORACLE;
        }  if(dto.getDriverClass().contains("dm")){
            dbType = DbType.DM;
        }

        DbHelper dbHelper = DbHelperFactory.getDbHelper(dbType, dto.getUrl(),dto.getUserName(),dto.getPassword(),null);
        if (dbHelper == null){
            return  false;
        }
        return dbHelper.testConnection();
    }

    @Override
    public List<Map<String, Object>> dynamicQuery(DynamicQueryDto dto) throws Exception {
        XjrVisualDb visualDb = this.getById(dto.getId());
        if(visualDb == null)
            throw  new Exception("没有找到数据源！");

        DbType dbType = DbType.MYSQL;
        if(visualDb.getDriverClass().contains("mysql")){
            dbType = DbType.MYSQL;
        }
        if(visualDb.getDriverClass().contains("sqlserver")){
            dbType = DbType.SQL_SERVER;
        }  if(visualDb.getDriverClass().contains("postgresql")){
            dbType = DbType.POSTGRE_SQL;
        }  if(visualDb.getDriverClass().contains("oracle")){
            dbType = DbType.ORACLE;
        }  if(visualDb.getDriverClass().contains("dm")){
            dbType = DbType.DM;
        }
        DbHelper dbHelper = DbHelperFactory.getDbHelper(dbType, visualDb.getUrl(), visualDb.getUserName(),visualDb.getPassword(),null);
        if (dbHelper == null){
            throw  new Exception("数据源链接错误！");
        }

        return dbHelper.getDataMapBySql(dto.getSql());

    }
}
